<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'education_name'
    ];

    public static $education = [
        0 => '小学',
        1 => '初中',
        2 => '高中',
        3 => '专科',
        4 => '本科',
        5 => '硕士',
        6 => '博士',
    ];

    public static $userPosition = [
        '100'   => '爷爷',
        '101'   => '奶奶',
        '200'   => '父亲',
        '201'   => '母亲',
        '300'   => '老公',
        '301'   => '老婆',
        '400'   => '兄弟',
        '401'   => '姐妹',
        //'402'   => '嫂子 / 弟媳',
        //'403'   => '姐夫 / 妹夫',
        '500'   => '儿子',
        '501'   => '女儿',
        '502'   => '儿媳',
        '503'   => '女婿',
    ];
    public static $userGender = [
        '0' => [101,201,301,401,402,501,502],
        '1' => [100,200,300,400,403,500,503]
    ];

    public function getRewardAttr($value){
        return floor($value);
    }

    public function experience(){
        return $this->hasMany('Experience','user_id','id')->order('start_time','desc');
    }

    public function getEducationNameAttr($value,$data){
        return self::$education[$data['education']];
    }

    /**
     * 获取头像
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param   string $value
     * @param   array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 生成邀请码
     * @param int $length
     * @return string
     */
    public static function generateInviteCode($length = 8)
    {
        $str = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
        $strlen = strlen($str);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $rand = mt_rand(0, $strlen - 1);
            $code .= $str{$rand};
        }
        $result = self::where('invite_code', $code)->count();
        if ($result > 0) {
            return self::generateInviteCode();
        }
        return $code;
    }

    /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from     [起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to     [终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    public static function getDistance($from,$to,$km=true,$decimal=2){
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数

        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;

        if($km){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }


    /**
     * @param $userId 用户id
     * @param $coinId 币种id
     * @param $money   额度
     * @param $changeType 类型
     * @param string $remark 备注
     * @param string $txid 流水id
     * @param string $extra 扩展
     * @param int $status
     */
    public static function setMoney($userId,$coinId, $money, $changeType, $remark = '', $txid = '', $status = 1)
    {
        //$coinId = 'money';
        if ($money == 0) {
            return false;
        }
        Db::startTrans();
        try {

            $count = GxHistory::where('txid',$txid)->where('change_type',$changeType)->lock(true)->count();
            if($count > 0){
                throw new Exception('记录已存在,txid:'.$txid.'---change_type:'. $changeType);
            }

            // 增加用户余额
            $userInfo = self::where('id', $userId)->lock(true)->find();
            $beforeBalance = $userInfo[$coinId];

            if($beforeBalance + $money < 0){
                throw new Exception('资产不足');
            }
            //sleep(1);
            self::where('id', $userId)->where($coinId,$beforeBalance)->update([$coinId=>$userInfo[$coinId] + $money]);

            if (empty($txid)) {
                $txid = generateUniqid();
            }

            $change = GxHistory::create([
                'user_id' => $userId,
                'coin_id' => $coinId,
                'amount' => $money,
                'before_balance' => assetsIntercept($beforeBalance, 18),
                'after_balance' => assetsIntercept($beforeBalance + $money, 18),
                'txid' => $txid,
                'change_type' => $changeType,
                'status' => $status,
                'remark' => $remark,
            ]);
            if (!$change) {
                throw new \Exception('插入change失败');
            }
            $return['changeId'] = $change->getLastInsID();

            DB::commit();
            return $return;
        } catch (\Exception $e) {
            DB::rollBack();
            write_log('setMoney方法错误----' . $e->getMessage() . '---' . $e->getLine(), '修改资产错误');
            return false;
        }
    }

    /**
     * @param $userId 用户id
     * @param $type 提醒类型 1=生日,2=祭祀
     */
    public static function getRemindUser($userId,$type){
        $ids = Attention::where('user_id',$userId)->column('att_user_id');
        if($type == 1){
            $sym = 'IS NULL';
            $field = 'birthday';
        }else{
            $sym = 'IS NOT NULL';
            $field = 'die_time';
        }
        $year = date('Y');
        $toDay = date('Y-m-d');
        $sDay = date('Y-m-d',strtotime('+3 day'));

        $list = self::where('id','IN',$ids)->where('die_time '.$sym)->field('id,nickname,avatar,birthday,die_time,education,DATE_FORMAT('. $field .', "'.$year.'-%m-%d") as format_birthday')->having('format_birthday >= "'. $toDay .'" AND format_birthday <= "'. $sDay .'"')->select();
        //echo '<pre>';print_r($list);die;
        return $list;
    }

    public static function liufangJl($money,$fid){
        $rate = Config::getValue('lf_rate1','basic') / 100;
        $rate2 = Config::getValue('lf_rate2','basic') / 100;
        $family = FamilyTree::where('id',$fid)->find();
        if(empty($family)){
            return false;
        }
        $userId = $family['user_id'];
        if(empty($userId)){
            return false;
        }
        $parent = self::where('id',$userId)->value('parent');
        if($parent == 0){
            return true;
        }else{
            $parentInfo = self::where('id',$parent)->find();

            // 上级分佣
            self::setMoney($parent,'money',$rate*$money,'7000','下级流芳奖励');

            // 上级分佣（二级）
            if($parentInfo['parent'] != 0){
                self::setMoney($parentInfo['parent'],'money',$rate2*$money,'7100','下级流芳奖励(二级)');
            }

            // 省 分佣
            $sheng = self::where('daili',3)->where('province',$family['province'])->value('id');
            if(!empty($sheng)){
                $shengRate = Config::getValue('lf_sheng_rate','basic') / 100;
                self::setMoney($sheng,'money',$shengRate*$money,'7200','省代理奖励');
            }
            // 市 分佣
            $shi = self::where('daili',2)->where('province',$family['province'])->where('city',$family['city'])->value('id');
            if(!empty($shi)){
                $shiRate = Config::getValue('lf_shi_rate','basic') / 100;
                self::setMoney($shi,'money',$shiRate*$money,'7300','市代理奖励');
            }
            // 区 分佣
            $qu = self::where('daili',1)->where('province',$family['province'])->where('city',$family['city'])->where('area',$family['area'])->value('id');
            if(!empty($qu)){
                $quRate = Config::getValue('lf_qu_rate','basic') / 100;
                self::setMoney($qu,'money',$quRate*$money,'7400','区代理奖励');
            }
            //$moneyRate = Config::getValue('recharge_rate','family_tree');
            //return self::liufangdg($money*$moneyRate*0.7,$parent,$rate);
        }
    }

    private static function liufangdg($money,$userId,$rate){
        $user = self::where('id',$userId)->field('id,parent')->find();
        if($user['parent'] == 0){
            self::setMoney($user['id'],'money',$money,'7000','下级流芳奖励');
            return true;
        }else{
            $bl = $money*$rate;
            self::setMoney($user['id'],'money',$bl,'7000','下级流芳奖励');
            return self::liufangdg($money-$bl,$user['parent'],$rate);
        }
    }
}
